package org.iteam.bank.notify.action;

import java.util.Arrays;

import org.apache.struts2.convention.annotation.Action;
import org.iteam.bank.mina.utils.ConfigLoader;
import org.iteam.bank.mina.utils.HexUtils;
import org.iteam.commons.codec.AESCoder;
import org.iteam.commons.codec.HMACCoder;
import org.iteam.mina.Constant;
import org.iteam.web.struts.action.JsonServletAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@SuppressWarnings("unchecked")
public class IndexAction extends JsonServletAction {
	private static Logger logger = LoggerFactory.getLogger(IndexAction.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 5820696029301355880L;
	private String params;// 绑卡加密参数
	private String sign;// 绑卡加密签名

	@Action("/signed")
	public String bindCard() {
		logger.debug("绑卡结果通知:{}", JSON.toJSONString(request.getParameterMap()));

		try {
			// 验证签名
			byte[] content = HexUtils.decodeHexByte(params);
			byte[] oldSign = HexUtils.decodeHexByte(params);
			// bindCard.KEY_HMAC
			// bindCard.KEY_AES
			byte[] sign = HMACCoder.encryptHMAC(content, ConfigLoader.get("gsp.KEY_HMAC"));
			if (Arrays.equals(sign, oldSign)) {
				// 签名验证成功，进入解密流程
				byte[] eContent = AESCoder.decrypt(content, ConfigLoader.get("gsp.KEY_AES"));
				JSONObject params = JSON.parseObject(new String(eContent, Constant.UTF_8));
				logger.debug("绑卡通知参数[解密后]:{}", params.toJSONString());
				String p2p_user_id = params.getString("p2p_user_id");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			map.put("state", false);
			map.put("info", e.getMessage());
		}
		logger.debug("绑卡结果返回:{}", JSON.toJSONString(map));
		return MAP;
	}

	@Action("/subscribe")
	public String subscribe() {
		logger.debug("认购结果通知:{}", JSON.toJSONString(request.getParameterMap()));

		try {
			// 验证签名
			byte[] content = HexUtils.decodeHexByte(params);
			byte[] oldSign = HexUtils.decodeHexByte(params);
			// bindCard.KEY_HMAC
			// bindCard.KEY_AES
			byte[] sign = HMACCoder.encryptHMAC(content, ConfigLoader.get("gsp.KEY_HMAC"));
			if (Arrays.equals(sign, oldSign)) {
				// 签名验证成功，进入解密流程
				byte[] eContent = AESCoder.decrypt(content, ConfigLoader.get("gsp.KEY_AES"));
				JSONObject params = JSON.parseObject(new String(eContent, Constant.UTF_8));
				logger.debug("认购通知参数[解密后]:{}", params.toJSONString());
				String p2p_user_id = params.getString("p2p_user_id");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			map.put("state", false);
			map.put("info", e.getMessage());
		}
		logger.debug("认购结果返回:{}", JSON.toJSONString(map));
		return MAP;
	}

	public String getParams() {
		return params;
	}

	public void setParams(String params) {
		this.params = params;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

}
